package com.ihrm.system.service;

import com.ihrm.common.service.BaseService;
import com.ihrm.common.util.IdWorker;
import com.ihrm.domain.system.Role;
import com.ihrm.domain.system.User;
import com.ihrm.system.dao.RoleDao;
import com.ihrm.system.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

@Service
public class UserService extends BaseService{
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 1,保存部门
     */
    public void add(User user){
        String id = idWorker.nextId()+"";
        user.setId(id);
        userDao.save(user);
    }

    /**
     * 2，更新部门
     */
    public void update(User user){
        User target = userDao.findById(user.getId()).get();
        //设置部门属性
        target.setUsername(user.getUsername());
        target.setPassword(user.getPassword());
        target.setDepartmentId(user.getDepartmentId());
        target.setDepartmentName(user.getDepartmentName());
        //更新部门
        userDao.save(target);
    }

    /**
     * 3，根据id查询部门
     */
    public User findById(String id){
        return userDao.findById(id).get();
    }

    /**
     * 4，查询全部
     *  参数：map集合的形式
     *      hasDept
     *      departmentId
     *      companyId
     */
    public Page findAll(Map<String,Object> map,int page,int size){

        /**
         * 用户构造查询条件
         */
        Specification<User> spec = new Specification<User>() {
           //动态拼接查询条件
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                ArrayList<Predicate> list = new ArrayList<>();
                //根据请求的companyid是否为空构造查询条件
                if(StringUtils.isEmpty(map.get("companyId"))){
                    list.add(criteriaBuilder.equal(root.get("companyId").as(String.class),(String)map.get("companyId")));
                }
                //根据请求的部门id构造查询条件
                if(!StringUtils.isEmpty(map.get("departmentId"))){
                    list.add(criteriaBuilder.equal(root.get("departmentId").as(String.class),(String)map.get("departmentId")));
                }
                //根据请求的是否分配部门构造查询条件 0未分配 1已分配
               if(!StringUtils.isEmpty(map.get("hasDept"))){
                   if(StringUtils.isEmpty(map.get("hasDept")) || "0".equals((String)map.get("hasDept"))){
                       list.add(criteriaBuilder.isNotNull(root.get("departmentId")));
                   }else{
                       list.add(criteriaBuilder.isNotNull(root.get("departmentId")));
                   }
               }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        };

        //分页 page页码  size条数
        Page<User> userPage = userDao.findAll(spec, new PageRequest(page-1, size));
        return userPage;
    }

    /**
     * 5，根据id删除部门
     */
    public void deleteById(String id){
        userDao.deleteById(id);
    }

    public void assignRoles(String userId, List<String> roleIds) {
        User user = userDao.findById(userId).get();
        Set<Role> set = new HashSet<>();
        for (String rId : roleIds) {
            Role role = roleDao.findById(rId).get();
            set.add(role);
        }
        user.setRoles(set);
        userDao.save(user);
    }

    //
    public User findByMobile(String mobile){
        User user = userDao.findByMobile(mobile);
        return user;
    }
}
